<script setup lang="ts">
import { showToast, type ActionSheetAction } from 'vant';
import { computed, onMounted, ref } from 'vue';

import base64ToBlob from 'b64-to-blob'
import { request } from '@/api';

interface birthType {
  selectedValues: string[];
  selectedOptions: {
    text: string;
    value: string;
  }[];
  selectedIndexes: number[];
}

interface areaType {
  selectedValues: string[];
  selectedOptions: {
    name: string;
    code: string;
  }[];
  selectedIndexes: number[];
}

const isShow = ref(false)
const isShowBirth = ref(false)
const isShowArea = ref(false)
const columns = ref<AreaDataItem[]>([]);
const isShowProfession = ref(false)
const profile = ref({} as HDMUser)
const birthList = computed(() => {
  return profile.value.birthday.split('-');
})

const columnsProfession = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]

const onSelectAvatar = async (action: ActionSheetAction, index: number) => {
  isShow.value = false
  if (index === 0) {
    // 相册上传
    const data = await HDM.pickerPhoto()
    onUpdateAvatar(data)
  } else if (index === 1) {
    // 拍照上传
    const data = await HDM.pickerCamera()
  }
}

const onUpdateAvatar = async (data: string) => {
  try {
    const image = base64ToBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post('member/profile/avatar', fd)
    profile.value.avatar = res.data.result.avatar
    const user = HDM.getUser()
    user.avatar = res.data.result.avatar
    HDM.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (err) {
    console.log('失败' + JSON.stringify(err))
    showToast({ message: '上传失败' })
  }
}

const onSelectBirth = (data: birthType) => {
  console.log(data.selectedValues)
  profile.value.birthday = data.selectedValues.join('-')
  isShowBirth.value = false
}

const onSelectArea = (data: areaType) => {
  const select = data.selectedOptions
  console.log(select)
  console.log(select[0].name + '  ' + select[0].code)
  console.log(select[1].name + '  ' + select[1].code)
  console.log(select[2].name + '  ' + select[2].code)
  profile.value.fullLocation = [select[0].name, select[1].name, select[2].name].join(' ')
  profile.value.provinceCode = select[0].code
  profile.value.cityCode = select[1].code
  profile.value.countyCode = select[2].code
  isShowArea.value = false
}

const onChangeProfession = (data: { selectedValues: string[] }) => {
  profile.value.profession = data.selectedValues[0]
  isShowProfession.value = false
}


const onSubmit = async () => {
  console.log(profile.value)
  // mk.vibrator()
  const res = await request.put('member/profile', profile.value)
  HDM.updateUser(res.data.result)
  showToast({ message: '保存成功' })
}

onMounted(() => {
  columns.value = HDM.getAreaColumns()
  profile.value = HDM.getUser()
  console.log(profile)
})



</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar">
      </van-image>
      <div class="avatar-btn" @click="isShow = true">
        <span>修改头像</span>
      </div>
    </div>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field label="昵称" v-model="profile.nickname" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model:model-value="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" v-model="profile.birthday" @click="isShowBirth = true" readonly
        placeholder="请选择日期"></van-field>
      <van-field label="所在地" v-model="profile.fullLocation" @click="isShowArea = true" readonly
        placeholder="请选择所在地"></van-field>
      <van-field label="职业" v-model="profile.profession" @click="isShowProfession = true" readonly
        placeholder="请选择职业"></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button @click="onSubmit" round block type="primary">
        保存资料
      </van-button>
    </div>

    <van-action-sheet title="修改头像" v-model:show="isShow" :actions="[{ name: '相册' }, { name: '拍照' }]"
      @select="onSelectAvatar" cancel-text="取消" :style="{ paddingBottom: '20px' }"></van-action-sheet>

    <VanPopup v-model:show="isShowBirth" position="bottom">
      <VanDatePicker title="选择日期" v-model:model-value="birthList" @cancel="isShowBirth = false"
        :min-date="new Date('1900-01-01')" :max-date="new Date()" @confirm="onSelectBirth"></VanDatePicker>
    </VanPopup>

    <VanPopup v-model:show="isShowArea" position="bottom">
      <VanPicker :columns-field-names="{ text: 'name', value: 'code', children: 'areaList' }"
        @cancel="isShowArea = false" @confirm="onSelectArea" title="选择地址" :columns="columns">
      </VanPicker>
    </VanPopup>

    <VanPopup v-model:show="isShowProfession" position="bottom">
      <VanPicker @cancel="isShowArea = false" @confirm="onChangeProfession" title="选择职业" :columns="columnsProfession">
      </VanPicker>
    </VanPopup>

  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px #ccc;
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
